package com.lw.leetcode.arr.c;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * 1224. 最大相等频率
 *
 * @author liw
 * @version 1.0
 * @date 2022/4/19 14:12
 */
public class MaxEqualFreq {


    public static void main(String[] args) {
        MaxEqualFreq test = new MaxEqualFreq();

        // 7
//        int[] arr = {2, 2, 1, 1, 5, 3, 3, 5};

        // 2
        int[] arr = {2, 2};

        // 13
//        int[] arr = {1,1,1,2,2,2,3,3,3,4,4,4,5};

        // 6
//        int[] arr = {6,6,6,6,6,6};

        // 13
//        int[] arr = {1,1,1,2,3,3,3,4,4,4,5,5,5,42,97,5,46,53,100,63,27,12,83,82,21,77,58,93,86,5,72,16,23,99,88,47,96,16,26,89,41,19,40,42,78,43,29,51,50,92,76,76,54,7,46,93,26,56,94,34,100,26,97,60,73,46,31,26,2,50,15,55,42,64,30,72,18,8,58,50,81,84,60,91,2,3,48,65,65,5,49,31,9,78,94,32,11,33,31,53,19,92,14,94,27,65,92,14};
//        int[] arr = {1, 1, 1, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 42};

        int i = test.maxEqualFreq(arr);
        System.out.println(i);

    }

    public int maxEqualFreq(int[] nums) {
        int length = nums.length;
        if (length < 3) {
            return length;
        }
        Map<Integer, Integer> map = new HashMap<>();
        int a = 0;
        int ac = 0;
        int b = 0;
        int bc = 0;
        int max = 0;
        for (int i = 0; i < length; i++) {
            int v = nums[i];
            int c = map.getOrDefault(v, 0) + 1;
            map.put(v, c);
            if (c > a) {
                if (ac > 1) {
                    b = a;
                    bc = ac - 1;
                }
                a = c;
                ac = 1;
            } else if (c == a) {
                ac++;
                bc--;
            } else if (c > b) {
                b = c;
                bc = 1;
            } else if (c == b) {
                bc++;
            } else {
                if (bc == 0) {
                    bc = 1;
                    b = c;
                }
            }
            int as = ac * a;
            int bs = bc * b;
            if (ac == i + 1 || as == i || (as == i + 1 && ac == 1) || (ac == 1 && b + 1 == a && as + bs == i + 1)) {
                max = i;
            }
        }
        return max + 1;
    }

}
